package org.wisdom.data.jpa.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.util.Assert;
import org.wisdom.data.jpa.entity.ObjectEntity;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 仓储工厂
 *
 * @author zhangzhiyan
 * @date 2022/04/15 12:59
 **/
@SuppressWarnings("NullableProblems")
public class WisdomJpaRepositoryFactoryBean<T extends JpaRepository<S, K>, S extends ObjectEntity,
    K extends Serializable> extends JpaRepositoryFactoryBean<T, S, K> {
    public WisdomJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new BaseRepositoryFactory(em);
    }

    @SuppressWarnings("rawtypes")
    private static class BaseRepositoryFactory extends JpaRepositoryFactory {

        public BaseRepositoryFactory(EntityManager em) {
            super(em);
        }

        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information,
            EntityManager entityManager) {
            JpaEntityInformation<?, Serializable> entityInformation =
                this.getEntityInformation(information.getDomainType());
            Object repository =
                this.getTargetRepositoryViaReflection(information, entityInformation, entityManager);
            Assert.isInstanceOf(WisdomRepositoryImpl.class, repository);
            return (JpaRepositoryImplementation)repository;
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return WisdomRepositoryImpl.class;
        }
    }
}
